﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
using Newtonsoft.Json;

namespace SPMS.Common
{
    /// <summary>
    /// 扩展JSON格式的响应类
    /// </summary>
    public class JsonResultEx : JsonResult
    {
        #region ---Constructor

        /// <summary>
        /// 初始化类型<see cref="JsonResultEx"/>的新实例。
        /// </summary>
        public JsonResultEx()
            : base()
        {
        }

        /// <summary>
        /// 初始化类型<see cref="JsonResultEx"/>的新实例。
        /// </summary>
        /// <param name="data">要序列化为JSON格式的对象实例。</param>
        public JsonResultEx(object data)
            : base()
        {
            //保存参数
            this.Data = data;
        }

        /// <summary>
        /// 初始化类型<see cref="JsonResultEx"/>的新实例。
        /// </summary>
        /// <param name="data">要序列化为JSON格式的对象实例。</param>
        /// <param name="behavior">处理请求行为。</param>
        public JsonResultEx(object data, JsonRequestBehavior behavior)
            : base()
        {
            //保存参数
            this.Data = data;
            this.JsonRequestBehavior = behavior;
        }

        #endregion

        #region ---Public Method

        /// <summary>
        /// 处理返回结果。
        /// </summary>
        /// <param name="context">控制器上下文。</param>
        /// <remarks></remarks>
        public override void ExecuteResult(ControllerContext context)
        {
            //判定上下文是否为空引用
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            //判定请求方法是否合法
            if ((this.JsonRequestBehavior == JsonRequestBehavior.DenyGet) && string.Equals(context.HttpContext.Request.HttpMethod, HttpMethod.Get.Method, StringComparison.OrdinalIgnoreCase))
            {
                throw new InvalidOperationException(SPMS.Common.Properties.Resources.JsonRequest_GetNotAllowed);
            }

            //获得反馈对象
            HttpResponseBase response = context.HttpContext.Response;

            //判定是否设置了反馈内容
            if (!string.IsNullOrEmpty(this.ContentType))
            {
                //设置反馈内容
                response.ContentType = this.ContentType;
            }
            else if (context.RequestContext.HttpContext.Request.Files.Count > 0)
            {
                //判断是否上传文件，如果是上传文件需要设置为HTML，以避免在IE下提示下载
                response.ContentType = SPMS.Common.Properties.Resources.text_content_type_html;
            }
            else
            {
                //设置默认反馈内容
                response.ContentType = SPMS.Common.Properties.Resources.text_content_type_json;
            }

            //判定是否设置了编码
            if (this.ContentEncoding != null)
            {
                //设置内容编码
                response.ContentEncoding = this.ContentEncoding;
            }
            else
            {
                //设置内容编码
                response.ContentEncoding = System.Text.Encoding.UTF8;
            }

            //判定是否需要序列化数据
            if (this.Data != null)
            {
                //创建转换器
                JsonConverter[] converters = new JsonConverter[]
                {
                    //日期转换器
                    new Newtonsoft.Json.Converters.JavaScriptDateTimeConverter()
                };

                //创建序列化器设置
                JsonSerializerSettings settings = new JsonSerializerSettings()
                {
                    NullValueHandling = NullValueHandling.Ignore,
                    Converters = converters
                };

                //创建序列化器
                JsonSerializer serializer = JsonSerializer.Create(settings);

                //序列化数据
                serializer.Serialize(response.Output, this.Data);
            }
        }

        #endregion
    }
}
